package com.treasure.mall.zbqmallapi.controller.contact;

import com.alibaba.fastjson.JSON;
import com.treasure.mall.biz.dto.common.ChatMessageBodyDTO;
import com.treasure.mall.biz.dto.condition.ContactHistoryMessageCondition;
import com.treasure.mall.biz.entity.contact.ChatPO;
import com.treasure.mall.biz.entity.contact.ContactHistoryMessagePO;
import com.treasure.mall.biz.entity.user.MerchantPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.mapstruct.ContactMapStruct;
import com.treasure.mall.biz.remote.live.TencentIMService;
import com.treasure.mall.biz.service.core.contact.ChatService;
import com.treasure.mall.biz.service.core.contact.ContactHistoryMessageService;
import com.treasure.mall.biz.service.core.user.MerchantService;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbqmallapi.annotation.AccessControl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * <p> 客服相关接口
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallapi.controller.contact
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/8/11 4:26 下午
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 *
 */
@RestController
@RequestMapping("/contact")
public class ContactController {

    @Autowired
    private TencentIMService imService;

    @Autowired
    private ChatService chatService;
    @Autowired
    private ContactHistoryMessageService historyMessageService;
    @Autowired
    private MerchantService merchantService;


    /**
     * 获取聊天列表
     *
     * @param user
     * @return
     */
    @GetMapping("/chat/list")
    @AccessControl(needLogin = true)
    public ApiResult chatList(@CurrentUser UserPO user) {
        List<ChatPO> list = chatService.findAllByUserId(user.getUserId());
        return ApiResult.ok(ContactMapStruct.INSTANCE.pos2vos(list));
    }


    /**
     * 建立聊天室
     *
     * @param user
     * @param merchantId 商户ID
     * @return
     */
    @GetMapping("/createGroup/{merchantId}")
    @AccessControl(needLogin = true)
    public ApiResult createGroup(@CurrentUser UserPO user, @PathVariable Long merchantId) throws UnsupportedEncodingException {
        String groupName;
        MerchantPO merchantPO = merchantService.findById(merchantId);
        if (merchantPO == null) {
            groupName = "客服";
        } else {
            groupName = merchantPO.getData().getTitle();
        }
        String groupId = "service_" + user.getUserId() + "_" + merchantId.toString();
        groupId = DigestUtils.md5Hex(groupId.getBytes(Constant.ENCODING_UTF8));
        if (!chatService.exist(user.getUserId(), merchantId)) {
            imService.createGroup(groupId, "客服" + user.getUserId().toString() + merchantId.toString());
            chatService.createGroup(user, merchantId, groupId, groupName);
        } else {
            chatService.enableGroup(user.getUserId(), merchantId);
            chatService.resetUserNoReadCount(user.getUserId(), merchantId);
        }
        return ApiResult.ok(groupId);
    }

    /**
     * 重置未读数量
     *
     * @param user
     * @param merchantId
     * @return
     */
    @GetMapping("/reset/read/count/{merchantId}")
    @AccessControl(needLogin = true)
    public ApiResult resetNoReadCount(@CurrentUser UserPO user, @PathVariable Long merchantId) {
        chatService.resetUserNoReadCount(user.getUserId(), merchantId);
        return ApiResult.ok();
    }

    /**
     * 删除回话
     *
     * @param id 回话ID
     * @return
     */
    @GetMapping("/delete/group/{id}")
    @AccessControl(needLogin = true)
    public ApiResult deleteGroup(@PathVariable Long id) {
        chatService.deleteGroup(id);
        return ApiResult.ok();
    }

    /**
     * 添加客服历史消息
     *
     * @param user
     * @param merchantId 客服商户ID
     * @param dto
     * @return
     */
    @PostMapping("/history/add/{merchantId}")
    @AccessControl(needLogin = true)
    public ApiResult addHistoryMessage(@CurrentUser UserPO user, @PathVariable Long merchantId, @RequestBody ChatMessageBodyDTO dto) {
        dto.setTime(LocalDateTime.now());
        historyMessageService.save(user, merchantId, dto);
        //更新回复消息
        chatService.modifyLastMessage(user.getUserId(), merchantId, dto.getMessage());
        return ApiResult.ok();
    }

    /**
     * 获取客服历史消息日志
     *
     * @param user       用户
     * @param merchantId 客服商户ID
     * @return
     */
    @GetMapping("/history/message/{merchantId}")
    @AccessControl(needLogin = true)
    public ApiResult getLiveHistoryMessage(@CurrentUser UserPO user, @PathVariable Long merchantId,
                                           @RequestParam(required = false, defaultValue = "1") Integer page,
                                           @RequestParam(required = false, defaultValue = "20") Integer size
    ) {
        ContactHistoryMessageCondition condition = new ContactHistoryMessageCondition();
        condition.setMerchantId(merchantId);
        condition.setUserId(user.getUserId());
        Page<ContactHistoryMessagePO> pages = historyMessageService.findAll(page, size, condition);
        List<ChatMessageBodyDTO> list = new ArrayList<>();
        pages.getContent().forEach(item -> {
            if (StringUtils.isNotBlank(item.getMessageBody())) {
                ChatMessageBodyDTO messageBody = JSON.parseObject(item.getMessageBody(), ChatMessageBodyDTO.class);
                list.add(messageBody);
            }
        });
        chatService.resetUserNoReadCount(user.getUserId(), merchantId);
        return ApiResult.ok(list);
    }

}
